﻿using CrateMayhem.Common.Model;
using CrateMayhem.Common.Services;
using Windows.System;

namespace CrateMayhem.WinRT.ViewModel
{
    public class GameControlViewModel : CrateMayhem.Common.ViewModel.GameControlViewModel
    {
        private readonly IGameSettingsService gameSettingsService;

        public GameControlViewModel(IServiceFactory serviceFactory) : base(serviceFactory)
        {
            gameSettingsService = serviceFactory.Create<IGameSettingsService>();
        }

        public void PerformKeyPress(VirtualKey key)
        {
            if (gameSettingsService.IsControlKeyPress(
                f => IsControlKeyPress(ControlType.Retry, key), ControlType.Retry)) Retry();
            else if (gameSettingsService.IsControlKeyPress(
                f => IsControlKeyPress(ControlType.Undo, key), ControlType.Undo)) Undo();
            else if (gameSettingsService.IsMoveKeyPress(
                f => IsMoveKeyPress(MoveType.Up, key), MoveType.Up)) Move(MoveType.Up);
            else if (gameSettingsService.IsMoveKeyPress(
            f => IsMoveKeyPress(MoveType.Right, key), MoveType.Right)) Move(MoveType.Right);
            else if (gameSettingsService.IsMoveKeyPress(
            f => IsMoveKeyPress(MoveType.Down, key), MoveType.Down)) Move(MoveType.Down);
            else if (gameSettingsService.IsMoveKeyPress(
                f => IsMoveKeyPress(MoveType.Left, key), MoveType.Left)) Move(MoveType.Left);
        }

        private static bool IsControlKeyPress(ControlType control, VirtualKey key)
        {
            return key == VirtualKey.R && control == ControlType.Retry 
                || key == VirtualKey.U && control == ControlType.Undo;
        }

        private static bool IsMoveKeyPress(MoveType move, VirtualKey key)
        {
            if (key == VirtualKey.Up && move == MoveType.Up) return true;
            if (key == VirtualKey.Right && move == MoveType.Right) return true;
            if (key == VirtualKey.Down && move == MoveType.Down) return true;
            return key == VirtualKey.Left && move == MoveType.Left;
        }
    }
}
